'use client';

import { chakra } from '@chakra-ui/react'

function EditableInput({
    finishEdit = () => {},
    startEdit = () => {},
    value = '',
    isEditMode = false
}: {
    finishEdit?: (value: string) => void,
    startEdit?: () => void,
    value?: string,
    isEditMode?: boolean
}) {
    
    const submit = (value: string) => {
        finishEdit(value);
    }

    const onsubmit = (event: any) => {
        event.preventDefault();
        submit(event.target.elements.editName.value);
    }
    
    return isEditMode ? (
        <chakra.form onSubmit={onsubmit} w="100%">
            <chakra.input 
                name="editName" 
                autoFocus={true} 
                onBlur={(event) => submit(event.target.value)} 
                w="100%" 
                maxW="100%"
                fontSize="sm"
                px={1}
                py={0.5}
                bg="rgba(255, 255, 255, 0.9)"
                border="1px solid rgba(255, 165, 0, 0.5)"
                borderRadius="4px"
                _focus={{
                    outline: "none", 
                    borderColor: "rgb(255, 140, 0)",
                    boxShadow: "0 0 0 1px rgba(255, 165, 0, 0.3)"
                }} 
                defaultValue={value}
            />
        </chakra.form>
    ) : (
        <chakra.div 
            onDoubleClick={() => startEdit()} 
            w="100%" 
            maxW="100%"
            overflow="hidden" 
            textOverflow="ellipsis" 
            whiteSpace="nowrap"
            fontSize="sm"
            py={0.5}
            px={1}
            cursor="pointer"
            title={value}
            _hover={{
                bg: "rgba(255, 165, 0, 0.05)"
            }}
        >
            {value}
        </chakra.div>
    );
}

export default EditableInput;